package com.github.mqpearth.utils;

import android.util.Log;

import com.github.mqpearth.model.Entity;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * EmailUtil
 *
 * @author mpqearth
 * @date 2020/08/22 13:22
 */
public class EmailUtil {

    public static void sendMail(String host, Integer port, String username, String password, String email, String subject, String emailMsg) throws MessagingException {

        Properties props = new Properties();
        //设置发送的协议
        props.setProperty("mail.transport.protocol", "SMTP");

        //设置发送邮件的服务器
        props.setProperty("mail.smtp.host", host);
        props.setProperty("mail.smtp.port", String.valueOf(port));

        props.setProperty("mail.smtp.auth", "true");

        // 创建验证器
        Authenticator auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                //设置发送人的帐号和密码
                return new PasswordAuthentication(username, password);
            }
        };

        Session session = Session.getInstance(props, auth);

        // 2.创建一个Message，它相当于是邮件内容
        Message message = new MimeMessage(session);

        //设置发送者
        message.setFrom(new InternetAddress(username));

        //设置发送方式与接收者
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));

        //设置邮件主题
        message.setSubject(subject);

        //设置邮件内容
        message.setContent(emailMsg, "text/html;charset=utf-8");

        // 3.创建 Transport用于将邮件发送
        Transport.send(message);
    }

    public static void sendMail(Entity entity, String subject, String emailMsg) throws MessagingException {

        sendMail(entity.getHost(), entity.getPort(), entity.getUsername(), entity.getPassword(), entity.getEmail(), subject, emailMsg);
    }


    public static boolean androidSendMail(final Entity entity, final String subject, final String emailMsg) {
        final Integer[] status = {0};
        new Thread() {
            @Override
            public void run() {
                try {
                    EmailUtil.sendMail(entity, subject, emailMsg);
                    status[0] = 1;
                } catch (Exception e) {
                    Log.e("mail", e.getMessage());
                    status[0] = 2;
                }
            }
        }.start();
        while (status[0] == 0) {

        }
        if (status[0] == 1) {
            return true;
        } else {
            return false;
        }
    }

}
